package servlet;

import dao.UserDao;
import dao.UserDaoImpl;
import org.json.JSONObject;
import redis.RedisDao;
import redis.RedisDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author moyv
 * @描述 注册请求处理
 */
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        JSONObject requestObj = new JSONObject(req.getParameter("request"));
        int account = requestObj.getInt("account");
        String name = requestObj.getString("name");
        String password = requestObj.getString("password");
        int result = 0;
        UserDao dao = new UserDaoImpl();
        RedisDao dao1 = new RedisDaoImpl();
        if (dao.queryAccount(account)) {
            System.out.println(account);
            System.out.println("该用户已存在");
            result = 2;
        } else if (dao.queryName(name)) {
            System.out.println("用户名已存在请更换");
            result = 3;
        } else if (dao.insertUser(account, name, password)) {
            dao1.insertUser(account, name);
            result = 1;
        } else {
            System.out.println("1");
        }
        //        以json的形式存储数据
        JSONObject obj = new JSONObject();

        obj.put("result", result);

        // 设置响应内容类型
        resp.setContentType("text/json; charset=utf-8");
//        输出数据
        PrintWriter out = resp.getWriter();
        out.print(obj);

    }
}
